import { getItem, setItem, removeAllItem, removeitem as removeStorageItem } from '../../utils/storage'
import { ACCESS_TOKEN, REFRESH_TOKEN } from '../../constant'
import { getUserInfo, login, logout, refreshToken as updateToken } from '../../api/sys'
import router, { resetRouter } from '../../router'
import { setTimeStamp } from '../../utils/auth'
import { removeItem } from '../../utils/cookies'
export default {
  namespaced: true,
  state: () => ({
    // 用户相关
    accessToken: getItem(ACCESS_TOKEN) || '',
    refreshToken: getItem(REFRESH_TOKEN) || '',
    userinfo: {}
  }),
  mutations: {
    setToken(state: any, token: any) {
      state.accessToken = token.accessToken
      state.refreshToken = token.refreshToken
      setItem(ACCESS_TOKEN, token.accessToken)
      setItem(REFRESH_TOKEN, token.refreshToken)
    },
    cleanToken(state: any) {
      state.accessToken = ''
      state.refreshToken = ''
      removeStorageItem(ACCESS_TOKEN)
      removeStorageItem(REFRESH_TOKEN)
    },
    setUserInfo(state: any, userinfo: any) {
      state.userinfo = userinfo
    }
  },
  actions: {
    /**
     * 登录请求动作
     * @param userInfo
     */
    login({ commit }: any, userInfo: { username: string; password: string }) {
      return new Promise((resolve, reject) => {
        login(userInfo)
          .then((data: any) => {
            commit('setToken', data)
            setTimeStamp()
            resolve(data)
          })
          .catch((err: any) => {
            reject(err)
          })
      })
    },
    /**
     * 获取用户信息
     * @param commit
     */
    async getUserInfo({ commit }: any) {
      const res = await getUserInfo()
      // console.log(res)
      commit('setUserInfo', res)
      return res
    },
    /**
     * 退出登录
     */
    async logout({ commit }: any) {
      const res = await logout()
      commit('cleanToken')
      commit('setUserInfo', {})
      removeAllItem()
      resetRouter()
      removeItem('sId')
      router.push('/login')
    },
    /**
     * 重置站点
     */
    resetSite({ commit }: any) {
      commit('setToken', '')
      commit('setUserInfo', {})
      removeAllItem()
      resetRouter()
      removeItem('sId')
      router.push('/login')
    },
    /**
     * 刷新
     */
    async refreshToken({ commit }: any, data: {}) {
      const res = await updateToken(data)
      commit('setToken', res)
      return getUserInfo()
    }
  }
}
